package admission.ecnu.service;

import java.util.ArrayList;

import org.json.JSONObject;

import admission.ecnu.dao.teacherInfoDao;
import admission.ecnu.interfaces.IRnsService;
import admission.ecnu.mainservlet.RnsContext;
import admission.ecnu.object.DataManager;
import admission.ecnu.object.OTeacherInfo;

public class inputTeacherInfo implements IRnsService {

	@Override
	public void executeService(RnsContext context) throws Exception {

		/*
		 * 验证用户key值
		 */
		JSONObject obj = context.getJsonRequestObject();
		System.out.print(obj.toString());
		
		if(!DataManager.USER_ID.equals(obj.get("key"))){
			JSONObject jsonReturn = new JSONObject();
			jsonReturn.put("returnCode", DataManager.RETURN_WRONGKEY);
			context.setJsonResponseObject(jsonReturn);
			return;
		}
		
		String[] teacherStrArray = obj.getString("teacherInfo").split("$");
		ArrayList<OTeacherInfo> teacherList= new ArrayList<OTeacherInfo>();
		
		for(int i = 0; i< teacherStrArray.length; i++){
			OTeacherInfo newTeacher = new OTeacherInfo();
			String[] item = teacherStrArray[i].split(",");
			for(int j = 0; j<item.length; j++){
				String[] keyValue = item[j].split("=");
				if(keyValue[0].equals("teacherId"))newTeacher.setTeacherId(keyValue[1]);
				if(keyValue[0].equals("name"))newTeacher.setName(keyValue[1]);
				if(keyValue[0].equals("title"))newTeacher.setTitle(keyValue[1]);
				if(keyValue[0].equals("special"))newTeacher.setSpecial(keyValue[1]);
			}
			teacherList.add(newTeacher);
			System.out.print("new teacher"+i+": "+newTeacher.toString());
			
			newTeacher = null;
		}
		System.out.print(teacherList.toString());
		
		new teacherInfoDao().teacherInsert(teacherList);
		
		JSONObject jsonReturn = new JSONObject();
		jsonReturn.put("returnCode", DataManager.RETURN_SUCCESSFUL);
		context.setJsonResponseObject(jsonReturn);
	}
}